package com.hs.geek.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.Map;

/**
 * @Author: songhao
 * @Date: 2021/8/22
 * @Description: TODO
 */
public class HttpClientUtil {

    // Httpclient对象
    private CloseableHttpClient httpClient;

    public HttpClientUtil(){
        this.httpClient = HttpClients.createDefault();
    }

    /**
     * 发送get请求
     * @param queryUrl
     * @param paramMap
     * @throws Exception
     */
    public String doGet(String queryUrl, Map<String,Object> paramMap) throws Exception{
        // 返回结果
        String responseContent = null;
        URIBuilder urlBuilder = new URIBuilder(queryUrl);
        // 设置参数
        if(paramMap != null){
            for(Map.Entry<String,Object> paramEntry : paramMap.entrySet()){
                urlBuilder.setParameter(paramEntry.getKey(),paramEntry.getValue() + "");
            }
        }
        URI requetURI = urlBuilder.build();
        HttpGet httpGet = new HttpGet(requetURI);
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = this.httpClient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                //请求体内容
                responseContent = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseContent;
    }

    /**
     * 关闭连接
     */
    public void destroy(){
        if(this.httpClient != null){
            try {
                this.httpClient.close();
                this.httpClient = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
